﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using Database.Classes;
using System.Collections.Generic;


public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void UpdateSciences()
    {
        try
        {
            int intervalTime = int.Parse(GetConfigurationForOption("SmallUpdateInterval"));//in seconds
            double ScienceBonus = double.Parse(GetConfigurationForOption("ScienceBonus"));
            using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(@"SELECT     SUM(dbo.Planets.Labs + dbo.Planets.PopulationLevel) AS Expr1, dbo.Players.PlayerId, dbo.Players.Science, dbo.Players.Biology, dbo.Players.Economy, 
                      dbo.Players.Energy, dbo.Players.Math, dbo.Players.Physics, dbo.Players.Social, dbo.Players.CurrentScience, dbo.Players.ArtifactID, dbo.Players.ScienceNetwork
FROM         dbo.Planets INNER JOIN
                      dbo.Players ON dbo.Planets.OwnerID = dbo.Players.PlayerId
GROUP BY dbo.Players.PlayerId, dbo.Players.Science, dbo.Players.Biology, dbo.Players.Economy, dbo.Players.Energy, dbo.Players.Math, dbo.Players.Physics, dbo.Players.Social, 
                      dbo.Players.CurrentScience, dbo.Players.ArtifactID, dbo.Players.ScienceNetwork
HAVING      (dbo.Players.PlayerId > 1)", conn))
                {
                    SqlDataReader rdr = cmd.ExecuteReader();
                    Dictionary<string, double> commands = new Dictionary<string, double>();
                    while (rdr.Read())
                    {
                        int science = int.Parse(rdr["Science"].ToString());
                        int pId = int.Parse(rdr["PlayerID"].ToString());
                        int currentSci = int.Parse(rdr["CurrentScience"].ToString());
                        double currentScience = 0;// = UserDefinedFunctions.GetPlayerScience(pId, currentSci).Value;
                        switch (currentSci)
                        {
                            case 1:
                                currentScience = double.Parse(rdr["Biology"].ToString()); break;
                            case 2:
                                currentScience = double.Parse(rdr["Economy"].ToString()); break;
                            case 3:
                                currentScience = double.Parse(rdr["Energy"].ToString()); break;
                            case 4:
                                currentScience = double.Parse(rdr["Math"].ToString()); break;
                            case 5:
                                currentScience = double.Parse(rdr["Physics"].ToString()); break;
                            case 6:
                                currentScience = double.Parse(rdr["Social"].ToString()); break;
                            default: continue;
                        }
                        double sciH = (int)double.Parse(rdr["Expr1"].ToString());
                        int levelPoints = Equations.ScienceCost((int)currentScience);
                        double bonus = (1.0 + ScienceBonus * science);
                        //get bonus from artifact
                        string t = rdr["ArtifactID"] as string;
                        if (t != null)
                        {
                            switch (t)
                            {
                                case "AL": bonus += 0.1; break;
                                case "GL": bonus += 0.2; break;
                                case "AML": bonus += 0.3; break;
                                case "BHS": bonus += 0.35; break;
                                case "AF": bonus -= 0.45; break;
                                case "MOT": bonus += 0.2; break;
                            }
                        }
                        //not working corectly
                        if (bool.Parse(rdr["ScienceNetwork"].ToString()) == true )
                        {
                            bonus += 0.15;
                        }
                        //calc sci per H if less then 0 set to 0.01;
                        sciH = sciH * bonus;
                        if (sciH < 0)
                            sciH = 0.01;
                        //get percentage
                        double currentValue = (1.0 - (currentScience - (int)currentScience)) * levelPoints * 1.0;
                        double newValue = currentValue * 1.0 - sciH  / (double)(3600.0 / intervalTime);
                        double valueToStore;
                        if (newValue <= 0) //new level
                        {
                            valueToStore = 1.0 - (Equations.ScienceCost((int)currentScience + 1) + newValue) / Equations.ScienceCost((int)currentScience + 1) * 1.0 + (int)currentScience + 1;
                        }
                        else
                        {
                            valueToStore = 1.0 - (newValue) / levelPoints + (int)currentScience;
                        }
                        //store in the db
                        commands.Add(StoreScience(pId, currentSci), valueToStore);
                    }
                    rdr.Close();
                    cmd.Parameters.Add("@val", SqlDbType.Float);
                    foreach (string c in commands.Keys)
                    {
                        try
                        {
                            cmd.CommandText = c;
                            cmd.Parameters["@val"].Value = commands[c];
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            InsertNews(8, DateTime.Now, c + "\n\n<br/>" + ex.ToString());
                        }
                    }
                }

            }
        }
        catch (Exception ex)
        {
            InsertNews(8, DateTime.Now, ex.ToString());
        }
    }

    public static string StoreScience(int pId, int sciId)
    {
        switch (sciId)
        {
            case 1:
                return "Update Players Set Biology = @val Where PlayerID = " + pId.ToString();
            case 2:
                return "Update Players Set Economy = @val Where PlayerID = " + pId.ToString();
            case 3:
                return "Update Players Set Energy = @val Where PlayerID = " + pId.ToString();
            case 4:
                return "Update Players Set Math = @val Where PlayerID = " + pId.ToString();
            case 5:
                return "Update Players Set Physics = @val Where PlayerID = " + pId.ToString();
            case 6:
                return "Update Players Set Social = @val Where PlayerID = " + pId.ToString();
            default: return string.Empty;
        }
    }
};
